const fs = require('fs');
const path = require('path');

const COMMIT_EDITING_FILEPATH = process.argv[2];
const COMMIT_EDITING_FILE = path.resolve(COMMIT_EDITING_FILEPATH);

const inputMsg = fs.readFileSync(COMMIT_EDITING_FILE, 'utf8');
const match = inputMsg.match(/^(\w+)(\(.+\))?:\s*(.+)/);
// 读取项目配置文件
const CONFIG_FILE = path.resolve('.cz-config.js');
let useEmoji = false;

try {
  // 尝试加载 .cz-config.js 文件
  const config = require(CONFIG_FILE);
  useEmoji = config.useEmoji || false;
} catch (error) {
  // 如果 .cz-config.js 文件不存在或加载失败，尝试从 package.json 中读取
  try {
    const packageJson = require(path.resolve('package.json'));
    useEmoji = packageJson.config?.czCustomizable?.useEmoji || false;
  } catch (error) {
    console.warn('未找到配置文件，跳过 emoji 添加。');
  }
}

// 如果 useEmoji 为 false，直接退出脚本
if (!useEmoji) {
  process.exit(0);
}

const typeToEmojiMap = {
  feat: '🚀',
  fix: '🧩',
  docs: '📚',
  style: '🎨',
  refactor: '♻️',
  perf: '⚡️',
  test: '✅',
  build: '📦',
  ci: '🎡',
  chore: '🔨',
  revert: '⏪️'
};

if (match) {
  const [fullMatch, type, scope, subject] = match;
  const emoji = typeToEmojiMap[type.trim()];
  if (emoji) {
    const newMsg = `${type}${scope ? `(${scope})` : ''}: ${emoji} ${subject}`;
    fs.writeFileSync(COMMIT_EDITING_FILE, newMsg, 'utf8');
  }
}
